import router from './index'
import {
	setToken,
	removeToken,
	getToken
} from '@/utils/auth';
import store from '@/store'

router.beforeEach((to, from, next) => {

	const userToken = to.query.userToken
	userToken && setToken(userToken)

	try {
		const terminal = to.query.terminal
		terminal && localStorage.setItem('terminal', terminal)
	} catch (e) {
		console.error(e);
	}

	const localTerminal = localStorage.getItem('terminal')
	switch (to.path) {
		case '/login':
			if (getToken()) {
				if (localTerminal) {
					store.dispatch('LOGOUT')
				} else {
					next('/list')
				}
			}
			break;
		case '/list':
			if (localTerminal) {
				store.dispatch('LOGOUT')
				next('/')
			}
			break;
		default:
			break;
	}

	next()
})